<template>
  <je-modal
    ref="calendarModal"
    v-model:visible="taskVisible"
    :title="taskTitle"
    :button-align="'center'"
    class="je-task-modal"
    :resize="false"
  >
    <je-calendar
      v-model:value="value"
      :locale="locale"
      @panelChange="changeDate"
      @select="selectDate"
    >
      <!-- :valid-range="validRangeDate" -->
      <template #dateCellRender="{ current }">
        <ul class="events">
          <li v-for="item in getListTask(current)" :key="item.JE_SYS_CALENDAR_ID" class="task-item">
            <span class="task-badge" :style="{ 'background-color': item.CALENDAR_COLOR }"></span>
            <span class="task-name" :title="item.CALENDAR_TITLE"> {{ item.CALENDAR_TITLE }}</span>
          </li>
        </ul>
      </template>
    </je-calendar>
  </je-modal>
  <calendar-list />
</template>

<script>
  import { defineComponent, reactive, toRefs, onBeforeUnmount, onMounted, ref } from 'vue';
  import locale from 'ant-design-vue/lib/calendar/locale/zh_CN';
  import { Modal } from '@jecloud/ui';
  import VueEvent from '@/helper/event';
  import { dateFormat, getCurrentUser } from '@jecloud/utils';
  import dayjs from 'dayjs';
  import { Calendar } from 'ant-design-vue';
  import { GetCalendarSchedule } from '@/api';
  import CalendarList from '@/views/board-home/components/calendar-list.vue';
  import {
    HOME_CALENDAR_TASK_VISIBLE,
    HOME_CALENDAR_LIST_VISIBLE,
    HOME_CALENDAR_LIST_CLOSE,
    HOME_CALENDAR_CLOSE_MODAL,
    HOME_CALENDAR_UPDATE_SUCCESS,
    HOME_CALENDAR_OPEN_LIST,
  } from '@/helper/constant';
  export default defineComponent({
    name: 'CalendarTask',
    components: {
      JeModal: Modal,
      JeCalendar: Calendar,
      CalendarList,
    },
    setup() {
      const value = ref();
      const state = reactive({
        taskTitle: '日程',
        taskVisible: false,
        fullCalendar: null, //日程对象
        locale,
        curSelectDate: new Date(), //当前时间
        tasks: {}, //日程任务
        showTaskList: false, //显示任务列表
        selectTime: new Date(), //选中的时间
      });
      const methods = {
        showTaskModal() {
          //显示日程弹窗
          state.taskVisible = true;
        },
        initMyTask(curDate, refreshDate) {
          //初始化我的日程任务
          const userId = getCurrentUser()?.id;
          const startDate = dayjs(curDate).startOf('month').format('YYYY-MM-DD') + ' 00:00:00';
          const endDate = dayjs(curDate).endOf('month').format('YYYY-MM-DD') + ' 23:59:59';
          const param = {
            tableCode: 'JE_SYS_CALENDAR',
            limit: -1,
            startTime: startDate,
            endTime: endDate,
          };
          GetCalendarSchedule(param).then((res) => {
            if (res.code == 1000 && res.success) {
              let tasks = res.data.rows;
              const taskObj = {};
              for (let task of tasks) {
                const startDate1 = dayjs(task.CALENDAR_STARTTIME).toDate();
                const endDate1 = dayjs(task.CALENDAR_ENDTIME).toDate();
                // 计算任务周期å
                const days = dayjs(dateFormat(endDate1, 'YYYY-MM-DD')).diff(
                  dateFormat(startDate1, 'YYYY-MM-DD'),
                  'day',
                );
                // 为每一天增加任务新
                for (let i = 0; i <= days; i++) {
                  const dateStr = dateFormat(startDate1, 'YYYY-MM-DD');
                  taskObj[dateStr] = taskObj[dateStr] || [];
                  taskObj[dateStr].push(task);
                  startDate1.setDate(startDate1.getDate() + 1);
                }
              }
              state.tasks = taskObj;
              if (refreshDate) {
                let dateStr = dateFormat(refreshDate, 'YYYY-MM-DD');
                const tasks = state.tasks[dateStr];
                if (tasks) {
                  VueEvent.emit(HOME_CALENDAR_LIST_VISIBLE, tasks);
                } else {
                  VueEvent.emit(HOME_CALENDAR_LIST_VISIBLE, []);
                }
              }
            }
          });
        },
        changeDate(date) {
          //日期面板变化回调
          let temCurDate = date.toDate();
          if (dateFormat(temCurDate, 'YYYY-MM') != dateFormat(state.curSelectDate, 'YYYY-MM')) {
            // const todayStr = dateFormat(temCurDate, 'YYYY-MM-DD');
            methods.initMyTask(temCurDate);
            state.curSelectDate = temCurDate;
          }
        },
        selectDate(date) {
          //点击选择日期回调
          const todayStr = dateFormat(date.toDate(), 'YYYY-MM-DD');
          const tasks = state.tasks[todayStr];
          if (tasks) {
            state.curSelectDate = date.toDate();
            state.showTaskList = true;
            VueEvent.emit(HOME_CALENDAR_LIST_VISIBLE, tasks);
            VueEvent.emit(HOME_CALENDAR_OPEN_LIST);
          }
        },
        getListTask(value) {
          //获取对应时间的任务
          let dateStr = dateFormat(value.toDate(), 'YYYY-MM-DD');
          return state.tasks[dateStr];
        },
        cancelListModal() {
          //关闭任务列表弹窗
          state.showTaskList = false;
        },
        refreshTaskList() {
          //刷新任务列表数据
          methods.initMyTask(state.curSelectDate, state.curSelectDate);
        },
        validRangeDate() {
          //设置可以显示的日期
          return [
            dayjs(state.curSelectDate).startOf('month').format('YYYY-MM-DD'),
            dayjs(state.curSelectDate).endOf('month').format('YYYY-MM-DD'),
          ];
        },
      };
      onMounted(() => {
        methods.initMyTask(state.curSelectDate);
        VueEvent.on(HOME_CALENDAR_TASK_VISIBLE, methods.showTaskModal);
        VueEvent.on(HOME_CALENDAR_LIST_CLOSE, methods.cancelListModal);
        VueEvent.on(HOME_CALENDAR_UPDATE_SUCCESS, methods.refreshTaskList);
      });
      onBeforeUnmount(() => {
        VueEvent.off(HOME_CALENDAR_TASK_VISIBLE);
        VueEvent.off(HOME_CALENDAR_LIST_CLOSE);
        VueEvent.off(HOME_CALENDAR_UPDATE_SUCCESS);
      });
      return {
        value,
        ...toRefs(state),
        ...methods,
      };
    },
  });
</script>
<style>
  .je-task-modal .je-modal--body {
    margin-bottom: 20px;
  }
  .je-task-modal .je-modal--body .je-modal--content::-webkit-scrollbar {
    width: 0;
    height: 0;
  }
  .je-task-modal
    .je-modal--body
    .je-modal--content
    .ant-picker-cell
    .ant-picker-calendar-date-content::-webkit-scrollbar {
    width: 0;
    height: 0;
  }
  .je-task-modal .ant-picker-calendar-header .ant-radio-group {
    display: none;
  }
  .je-task-modal .je-modal--content .ant-picker-calendar-header {
    justify-content: flex-start;
  }
  .je-task-modal .je-modal--content .ant-picker-calendar-header .ant-select-selector {
    width: 110px;
  }
</style>
<style scoped lang="less">
  .events {
    list-style: none;
    margin: 0;
    padding: 0;
  }
  .events .ant-badge-status {
    overflow: hidden;
    white-space: nowrap;
    width: 100%;
    text-overflow: ellipsis;
    font-size: 12px;
  }
  .notes-month {
    text-align: center;
    font-size: 28px;
  }
  .notes-month section {
    font-size: 28px;
  }
  .je-task-modal .task-item {
    display: flex;
    align-items: center;
    .task-badge {
      width: 6px;
      height: 6px;
      border-radius: 50%;
      flex-shrink: 0;
    }
    .task-name {
      padding-left: 3px;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }
  }
</style>
